package com.qys.livesMall.shop.scheduledTask;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.qys.livesMall.shop.constants.OrderStatus;
import com.qys.livesMall.shop.constants.PayStatus;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuStocksMapper;
import com.qys.livesMall.shop.modal.entity.SeckillOrder;
import com.qys.livesMall.shop.modal.entity.ShopOrderIdea;
import com.qys.livesMall.shop.modal.entity.ShopOrderInfo;
import com.qys.livesMall.shop.modal.entity.ShopOrderSku;
import com.qys.livesMall.shop.service.SeckillOrderService;
import com.qys.livesMall.shop.service.ShopOrderIdeaService;
import com.qys.livesMall.shop.service.ShopOrderInfoService;
import com.qys.livesMall.shop.service.ShopOrderSkuService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @packageName:
 * @className:OrderScheduledTask
 * @Description:
 * @author:guomx
 * @date:2023/6/2314:47
 */
@Component
public class OrderScheduledTask {
    private static final Logger log = LoggerFactory.getLogger(OrderScheduledTask.class);
    @Resource
    private ShopOrderInfoService orderInfoService;

    @Resource
    private ShopOrderSkuService orderSkuService;
    @Resource
    private ShopGoodsSkuStocksMapper skuStocksMapper;
    @Resource
    private ShopOrderIdeaService ideaService;
    @Resource
    private SeckillOrderService seckillOrderService;
    //定时删除未支付的订单
    @Scheduled(cron = "0 0 3 * * ?") // 每天3点执行一次
    public void deleteOrderTask() {
        try {
            long halfHourAgoTimeStamp = System.currentTimeMillis() - (30 * 60 * 1000);
            LambdaQueryWrapper<ShopOrderInfo> orderInfoQueryWrapper = new LambdaQueryWrapper<>();
            orderInfoQueryWrapper.eq(ShopOrderInfo::getPayStatus, PayStatus.NONPAYMENT);
            orderInfoQueryWrapper.eq(ShopOrderInfo::getOrderStatus,OrderStatus.WAIT_PAY);
            orderInfoQueryWrapper.eq(ShopOrderInfo::getIsDelete,"0");
            orderInfoQueryWrapper.apply("create_time <= " + halfHourAgoTimeStamp);
            List<ShopOrderInfo> orderInfos=orderInfoService.list(orderInfoQueryWrapper);
            if (ObjectUtils.isEmpty(orderInfos)){
                return;
            }
            List<Long> orderInfoIds = orderInfos.stream().map(ShopOrderInfo::getId).collect(Collectors.toList());
            orderInfos=orderInfos.stream().peek(orderInfo->{
                orderInfo.setOrderStatus(OrderStatus.CANCELED);
            }).collect(Collectors.toList());
            List<ShopOrderIdea> ideas = new ArrayList<>();
            for (ShopOrderInfo orderInfo : orderInfos) {
                ShopOrderIdea idea = new ShopOrderIdea();
                idea.setIdea("Order overdue");
                idea.setOrderId(orderInfo.getId());
                idea.setDescription("Order overdue");
                idea.setCreateTime(System.currentTimeMillis());
                ideas.add(idea);
            }
            //秒杀订单
            List<SeckillOrder> seckillOrders=seckillOrderService.listByIds(orderInfoIds);
            if (CollectionUtils.isNotEmpty(seckillOrders)){
                for (SeckillOrder seckillOrder : seckillOrders) {
                    seckillOrder.setStatus(PayStatus.PAYMENT_FAILURE);
                }
                seckillOrderService.updateBatchById(seckillOrders);
            }
            LambdaQueryWrapper<ShopOrderSku> orderSkuQueryWrapper = new LambdaQueryWrapper<>();
            orderSkuQueryWrapper.in(ShopOrderSku::getOrderId,orderInfoIds);
            List<ShopOrderSku> orderSkus = orderSkuService.list(orderSkuQueryWrapper);
            for (ShopOrderSku orderSku : orderSkus) {
                orderSku.setOrderStatus(OrderStatus.CANCELED);
                orderSkuService.updateById(orderSku);
                Long stocksId = orderSku.getStocksId();
                Integer num = orderSku.getNum();
                skuStocksMapper.decount(stocksId,-num);
            }
            // 批量删除订单
            if (!orderInfos.isEmpty()) {
                orderInfoService.updateBatchById(orderInfos);
                ideaService.saveBatch(ideas);
                log.info("Cancel order size:[{}]", orderInfos.size());
            } else {
                log.info("There are no eligible orders to delete");
            }

            // 执行任务的逻辑代码
            log.info("Execute a scheduled task");
        }catch (Exception e){
            log.error("Error scheduled task: {}", e.getMessage());
        }

    }
}
